<?php
class OfferController extends Zend_Controller_Action
{
	protected $_searchIndex;
	
	public function init()
	{
		$title ="view an object";
		$this->view->__set("headtitle", $title);
		////Script for map 
		$script = '$(document).ready(function() {
		$(\'#francemap\').vectorMap({
		    map: \'france_fr\',
			hoverOpacity: 0.5,
			hoverColor: false,
			backgroundColor: "#ffffff",
			colors: couleurs,
			borderColor: "#000000",
			selectedColor: "#EC0000",
			enableZoom: true,
			showTooltip: true,
		    onRegionClick: function(element, code, region)
		    {
		        var message = \'Département : "\'
		            + region 
		            + \'" || Code : "\'
		            + code
					+ \'"\';
             
		        $(\'#department\').val(region);
				$(\'#code\').val(code);
		    }
		});
	});';
		$this->view->headScript()->appendScript($script, $type = 'text/javascript');
		$baseurl = $this->getFrontController()->getBaseUrl();
		$this->view->headLink()->appendStylesheet($baseurl."/france_jqvmap/jqvmap.css");
		$this->view->headScript()->appendFile( $baseurl."/france_jqvmap/jquery.vmap.js", $type = 'text/javascript' );
		$this->view->headScript()->appendFile( $baseurl."/france_jqvmap/jquery.vmap.france.js", $type = 'text/javascript' );
		$this->view->headScript()->appendFile( $baseurl."/france_jqvmap/jquery.vmap.colorsFrance.js", $type = 'text/javascript' );
		///////
		$path = APPLICATION_PATH.'search_index';
		try {
			$this->_searchIndex = Zend_Search_Lucene::open($path);
		} catch (Zend_Search_Lucene_Exception $e) {
				
			$this->_searchIndex = Zend_Search_Lucene::create($path);
				
		}

	}
	
	/**
	 * Upload the address from the form to the data base.
	 * 
	 * @param array $form
	 * @param string $depatement
	 * @param int $code_dep
	 * @return multitype:Application_Model_Address
	 */
	private function uploadAddress($form){
		
		$addresses = array();
		
		
		$addressValues = array(
				'text'			=> $form->getValue('address'),
				'zipCode'		=> $form->getValue('zipCode'),
				'city'			=> $form->getValue('city'),
				'latitude'			=> $form->getValue('latitude'),
				'longitude'			=> $form->getValue('longitude'),
				'admin_area_lvl1'	=> $form->getValue('admin_area_lvl1'),
				'admin_area_lvl2'	=> $form->getValue('admin_area_lvl2'),
				'country'		=> $form->getValue('country'),
		);
		$address = new Application_Model_Address($addressValues);
		$addressMapper = new Application_Model_AddressMapper();
		$id_address = $addressMapper->save($address);
		$address->setAddressId($id_address);
		$addresses[] = $address;
		return $addresses;
	}
	
	public function saleAction()
	{
		$auth = Zend_Auth::getInstance ();
		if ($auth->hasIdentity ()) {
			$form = new Application_Form_Sale('sale');
			$user = new Application_Model_User();
			$userMapper = new Application_Model_UserMapper();
			$user = $userMapper->find($auth->getIdentity ()->id_user);
			$class = $this->_request->getParam("class");
			$id_object = $this->_request->getParam("id_object");
			$name = $this->_request->getParam("name");
		
			try {
			
				if(Application_Model_Enum_ClassName::exist($class) != null){
					$class = Application_Model_Enum_ClassName::exist($class);
					$object = Application_Model_Factory_ObjectMapperFactory::find($id_object, $class);
						
					if($object != null && Application_Model_Tool_ObjectUrl::getObjectNameUrl($object->getName()) == $name)
					{
						$whereObject = array('id_object = ?' => $object->getObjectId());
						$offerMapper = new Application_Model_OfferMapper();
						$offer = $offerMapper->findWhere($whereObject);
						//verify if the user connected is the owner of the object
							
						$userConnected = new Application_Model_User();
						$userMapper = new Application_Model_UserMapper();
						$userConnected = $userMapper->find($auth->getIdentity ()->id_user);
						$objectOwner = $offer->getUser();
						$getObjectId = 'get'.$class.'Id';
						if($offer != null){
							$whereOffer = array('id_offer = ?' => $offer->getOfferId());
							if($offerMapper->isEmptyOffer($whereOffer) && $userConnected == $objectOwner )
							{
								$this->view->activeOffer = true;
								
								$this->view->object = $object;
								$title =$object->getName();
								$this->view->__set("headtitle", $title);
								
								if($this->_request->isPost()){
									$formData = $this->getRequest()->getPost();
									if($form->isValid($formData))
									{
										$sale = new Application_Model_Sale($form->getValues());
										$saleMapper = new Application_Model_SaleMapper();
										$sale->setUser($user);
										$sale->setObject($object);
										$sale->setPrice_currency('€');
										$sale->setStart_date(date('Y-m-d H:i:s'));
										$sale->setEnd_date(date('Y-m-d H:i:s', time() + 3600 * 24 * 30));
										$classe = get_class($object);
										$classe = explode("_",$classe);
										$classe = $classe[2];
										$sale->setClasse($classe);
										$sale->setId_classe($object->$getObjectId());
										$addresses = $this->uploadAddress($form);
										$sale->setAddresses($addresses);
										//pour récuperer l'id de l'offre
										$sale = $saleMapper->find($saleMapper->save($sale),$sale);
										
										// Create a new document Zend Search Lucene
										$doc = new Zend_Search_Lucene_Document();
										Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive());
										try {
											$address = $addresses[0];
											$addressMapper = new Application_Model_AddressMapper();
											$objectMapper = Application_Model_Factory_ObjectMapperFactory::load($class);
											$doc = $objectMapper->indexBuilder($doc,$object);
											$doc = $saleMapper->indexBuilder($doc, $sale);
											$doc = $addressMapper->indexBuilder($doc, $address);
										}catch (RuntimeException $e)
										{
											//@TODO
										}
										
										$this->_searchIndex->addDocument($doc);
										$this->_searchIndex->commit();
										$this->_searchIndex->optimize();
										
										
										$this->_helper->redirector($object->$getObjectId().'-'.Application_Model_Tool_ObjectUrl::getObjectNameUrl($object->getName()), strtolower($class), 'view' );
									
									}
								}
							}
							else{
								$this->view->alert = 'cet object ne vous appartient pas';
								$this->_helper->redirector($object->$getObjectId().'-'.Application_Model_Tool_ObjectUrl::getObjectNameUrl($object->getName()), strtolower($class), 'view' );
							}
						}
							
							
					}else{
						$this->view->alert = 'l\'object n\'existe pas';
						$this->view->object = null;
					}
			
				}else{
					$this->render('error');
				}
			
			}catch (Exception $e) {
				//echo 'Exception reçue : ',  $e->getMessage(), "\n";
				$this->view->alert = $e->getMessage();
			
			}
			
			$this->view->form = $form;
		}else{
				
			$this->_helper->redirector ( 'index', 'index' );
		}
		
	}
	
	public function rentAction()
	{
		$auth = Zend_Auth::getInstance ();
		if ($auth->hasIdentity ()) {
			$form = new Application_Form_Rent('rent');
			$user = new Application_Model_User();
			$userMapper = new Application_Model_UserMapper();
			$user = $userMapper->find($auth->getIdentity ()->id_user);
			
			$class = $this->_request->getParam("class");
			$id_object = $this->_request->getParam("id_object");
			$name = $this->_request->getParam("name");
			
			try {
					
				if(Application_Model_Enum_ClassName::exist($class) != null){
					$class = Application_Model_Enum_ClassName::exist($class);
					$object = Application_Model_Factory_ObjectMapperFactory::find($id_object, $class);
			
					if($object != null && Application_Model_Tool_ObjectUrl::getObjectNameUrl($object->getName()) == $name)
					{
						$whereObject = array('id_object = ?' => $object->getObjectId());
						$offerMapper = new Application_Model_OfferMapper();
						$offer = $offerMapper->findWhere($whereObject);
						//verify if the user connected is the owner of the object
							
						$userConnected = new Application_Model_User();
						$userMapper = new Application_Model_UserMapper();
						$userConnected = $userMapper->find($auth->getIdentity ()->id_user);
						$objectOwner = $offer->getUser();
						if($offer != null){
							$getObjectId = 'get'.$class.'Id';
							$whereOffer = array('id_offer = ?' => $offer->getOfferId());
							if($offerMapper->isEmptyOffer($whereOffer) && $userConnected == $objectOwner )
							{
								$this->view->activeOffer = true;
								
								$this->view->object = $object;
								$title =$object->getName();
								$this->view->__set("headtitle", $title);
								
								if($this->_request->isPost()){
									$formData = $this->getRequest()->getPost();
									if($form->isValid($formData))
									{
										$rent = new Application_Model_Rent($form->getValues());
										$rentMapper = new Application_Model_RentMapper();
										$rent->setUser($user);
										$rent->setObject($object);
										$rent->setPrice_currency('€');
										$rent->setStart_date(date('Y-m-d H:i:s'));
										$rent->setEnd_date(date('Y-m-d H:i:s', time() + 3600 * 24 * 30));
										$classe = get_class($object);
										$classe = explode("_",$classe);
										$classe = $classe[2];
										$rent->setClasse($classe);
										$rent->setId_classe($object->$getObjectId());
										$addresses = $this->uploadAddress($form);
										$rent->setAddresses($addresses);
										//pour récuperer l'id de l'offre
										$rent = $rentMapper->find($rentMapper->save($rent),$rent);
										
										// Create a new document Zend Search Lucene
										$doc = new Zend_Search_Lucene_Document();
										Zend_Search_Lucene_Analysis_Analyzer::setDefault(new Zend_Search_Lucene_Analysis_Analyzer_Common_TextNum_CaseInsensitive());
										try {
											$address = $addresses[0];
											$addressMapper = new Application_Model_AddressMapper();
											$objectMapper = Application_Model_Factory_ObjectMapperFactory::load($class);
											$doc = $objectMapper->indexBuilder($doc,$object);
											$doc = $rentMapper->indexBuilder($doc, $rent);
											$doc = $addressMapper->indexBuilder($doc, $address);
										}catch (RuntimeException $e)
										{
												//@TODO
										}
										
										$this->_searchIndex->addDocument($doc);
										$this->_searchIndex->commit();
										$this->_searchIndex->optimize();
										
										$this->_helper->redirector($object->$getObjectId().'-'.Application_Model_Tool_ObjectUrl::getObjectNameUrl($object->getName()), strtolower($class), 'view' );
											
									}
								}
							}
							else{
								$this->view->alert = 'cet object ne vous appartient pas';
								$this->_helper->redirector($object->$getObjectId().'-'.Application_Model_Tool_ObjectUrl::getObjectNameUrl($object->getName()), strtolower($class), 'view' );
								
							}
						}
							
							
					}else{
						$this->view->alert = 'l\'object n\'existe pas';
						$this->view->object = null;
					}
						
				}else{
					$this->render('error');
				}
					
			}catch (Exception $e) {
				//echo 'Exception reçue : ',  $e->getMessage(), "\n";
				$this->view->alert = $e->getMessage();
					
			}
			
			$this->view->form = $form;
		}else{
		
			$this->_helper->redirector ( 'index', 'index' );
		}
		
	}
	
	/**
	 * Function that control the last offer added in the data base 
	 */
	public function lastofferAction() {
		
		$offer = $this->_request->getParam("offer");
		$classe = get_class($offer);
		$classe = explode("_",$classe);
		$offerClass = strtolower($classe[2]);
		$class = $offer->getClasse();
		$user = $offer->getUser();
		$object = $offer->getObject();
		$addresses = $offer->getAddresses();
		
		$this->view->objectUrl = '/view/'.strtolower($class).'/'.$offer->getId_classe().'-'.Application_Model_Tool_ObjectUrl::getObjectNameUrl($object->getName());  
		$this->view->userUrl = '/profil/'.$offer->getUser()->getUserId();
		$this->view->offerClass = $offerClass;
		$this->view->classe = strtolower($class);
		$this->view->object = $object;
		$this->view->address = $addresses[0];
		$this->view->user = $user;
		$this->view->price = $offer->getPrice();
		$this->view->priceCurrency = $offer->getPrice_currency();
		$this->view->offer = $offer;
	}
}